package client;

import interfaces.Category;
import interfaces.Core;
import interfaces.Order;
import interfaces.Product;
import interfaces.ProductList;

import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NamingException;
import javax.swing.*;

import java.awt.*;
import java.awt.event.*;
import java.util.ArrayList;

public class ClientGUI extends JFrame
{
	private static final long serialVersionUID = -5199617154126219009L;
	private JButton button1, button2, button3, button4;
	private JPanel orderPanel, proButtPanel, productPanel, catePanel ;
	private JPanel buttonPanel,buttonOrderPanel;
	private JLabel appName, statusLabel;
	private JTextArea textArea;
	private JComboBox itemBox;
	private ArrayList<Category> cateList;
	private int size;
	private String userName,url;
	private User user;


	public ClientGUI(User user,String url)
	{
		super("Welcome to RMI-Store");
		setLocation(300,300);
		setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		getContentPane().setLayout(new BorderLayout());
		appName = new JLabel();
		System.setProperty( "java.security.policy", "client.policy" );
		this.url = url;
		this.user = user;
		try
		{
			Context namingContext = new InitialContext();
			userName = user.getUserName();
			Core core = (Core)namingContext.lookup(url + "core");
			cateList = (ArrayList<Category>)core.getCategories();
			size = cateList.size();
			if(size<=4)
			{
				catePanel = new JPanel(new GridLayout(size+1,1));
			}
			else
			{
				catePanel = new JPanel(new GridLayout(size/2,2));
			}
			for(Category cat : cateList)
			{
				String buttonName = cat.getName();
				JRadioButton  rB = new JRadioButton(buttonName);
				rB.setSelected(true);
				catePanel.add(rB);
			}
			appName.setText("Welcome "+ userName );
		}
		catch( NamingException e ) {
			System.out.println( "NamingError: " + e.getExplanation() ); 
		} catch( Exception e ) {
			System.out.println( "Error: " + e.getMessage() );
		}

		proButtPanel = new JPanel(new GridLayout(2,1));
		buttonPanel = new JPanel(new GridLayout(1,2));
		buttonOrderPanel = new JPanel(new GridLayout(1,2));
		button1 = new JButton("Selecteer");
		button4 = new JButton("Annuleren");
		button3 = new JButton("Accepteren");
		button2 = new JButton("Verwijder");

		textArea = new JTextArea();
		orderPanel = new JPanel(new GridLayout(2,1));

		orderPanel.add(textArea);
		orderPanel.add(buttonOrderPanel);
		buttonPanel.add(button1);
		buttonPanel.add(button2);
		buttonOrderPanel.add(button3);
		buttonOrderPanel.add(button4);
		proButtPanel.add(catePanel);
		proButtPanel.add(buttonPanel);

		addButtonListener(button1);
		

		appName.setHorizontalAlignment(JLabel.CENTER); 

		statusLabel = new JLabel("Choose option");

		getContentPane().add(BorderLayout.NORTH,appName);
		getContentPane().add(BorderLayout.CENTER,proButtPanel);
		getContentPane().add(BorderLayout.EAST,orderPanel);
		getContentPane().add(BorderLayout.SOUTH,statusLabel);
		//pack();
		setSize(500, 400);
		setVisible(true);
	}

	private void addButtonListener(JButton b)
	{
		b.addActionListener(new ActionListener() 
		{ 
			public void actionPerformed(ActionEvent ae) 
			{ 
				input(user.getUserName()+" choose "+ae.getActionCommand());

				/*
				 * Doing a new order of one product
				 * 
				 */
				if( ae.getActionCommand().equalsIgnoreCase("Voeg toe") )
				{
					System.setProperty( "java.security.policy", "client.policy" );

					try {
						Context namingContext = new InitialContext();
						Core core = (Core)namingContext.lookup(url + "core");
						ProductList productList = (ProductList)core.getProductList();
						Order ord = core.getOrder(user.getUserName());
						Product product = null;
						Component[] cmp = productPanel.getComponents();
						for( int i = 0; i<cmp.length;i++ )
							if( ( itemBox = (JComboBox)cmp[i] ) != null && ( product = productList.get(itemBox.getSelectedItem().toString() ) ) != null ) 
							{
								core.addToOrder(userName, product, 1);
							}
						textArea.setText("");
						for(Product prod : ord.getProducts().keySet())
						{
							String pro = prod.getName();
							pro+=" price: "+prod.getPrice() + " number: " + ord.getProducts().get(prod);
							textArea.append(pro+"\n");
						}
						textArea.append("Total: "+ord.getTotal()+"\n");
					} catch (NamingException e) {
						e.printStackTrace();
					}
					catch( Exception e ) {
						System.out.println( "Error: " + e.getMessage() );
						e.printStackTrace();
					}
				}
				/*
				 * Getting the products out of catogories
				 * 
				 */
				else if( ae.getActionCommand().equalsIgnoreCase("Selecteer") )
				{
					System.setProperty( "java.security.policy", "client.policy" );
					try
					{
						addButtonListener(button2);
						addButtonListener(button3);
						addButtonListener(button4);
						Context namingContext = new InitialContext();
						userName = user.getUserName();
						Core core = (Core)namingContext.lookup(url + "core");
						ProductList productList = (ProductList)core.getProductList();
						Component[] cmp = catePanel.getComponents();
						JRadioButton catItem;
						ArrayList<Product> producten = new ArrayList<Product>();
						for( int i = 0; i<cmp.length;i++ )
							if( ( catItem = (JRadioButton)cmp[i] ) != null )
							{
								for( Product product : productList.getProductList() ) 
								{
									if(catItem.isSelected()&&catItem.getText().equalsIgnoreCase(product.getCategory().getName()))
										producten.add(product);
								}						
							}
						size = producten.size();
						if(size<=4)
						{
							productPanel = new JPanel(new GridLayout(size+1,1));
						}
						else
						{
							productPanel = new JPanel(new GridLayout(size/2,2));
						}
						int i = 0;
						String[] items = new String[size];
						for(Product p : producten)
						{
							String buttonName = p.getName();
							items[i] = buttonName;
							i++;							
						}
						itemBox = new JComboBox(items);
						productPanel.add(itemBox);
						button1.setText("Voeg toe");
						proButtPanel.remove(catePanel);
						proButtPanel.remove(buttonPanel);
						proButtPanel.add(productPanel);
						proButtPanel.add(buttonPanel);
						Order ord=null;
						if( ( ord = core.getOrder(userName) )!=null )
						{
							textArea.setText("");
							for(Product prod : ord.getProducts().keySet())
							{
								String pro = prod.getName();
								pro+=" price: "+prod.getPrice() + " number: " + ord.getProducts().get(prod);
								textArea.append(pro+"\n");
							}
							textArea.append("Total: "+ord.getTotal()+"\n");
						}

					} 
					catch (NamingException e)
					{
						e.printStackTrace();
					}
					catch( Exception e ) 
					{
						System.out.println( "Error: " + e.getMessage() );
						e.printStackTrace();
					}
				}
				/*
				 * Dropping one product
				 * 
				 */
				else if( ae.getActionCommand().equalsIgnoreCase("Verwijder") )
				{
					System.setProperty( "java.security.policy", "client.policy" );
					try {
						Context namingContext = new InitialContext();
						Core core = (Core)namingContext.lookup(url + "core");
						ProductList productList = (ProductList)core.getProductList();
						Product product = null;
						Component[] cmp = productPanel.getComponents();
						for(int i = 0; i<cmp.length;i++)

							if( ( itemBox = (JComboBox)cmp[i]) != null && ( product = productList.get( itemBox.getSelectedItem().toString() ) ) != null ) 
							{
								core.removeFromOrder(userName, product);
							}


					}
					catch (NamingException e)
					{
						e.printStackTrace();
					}
					catch( Exception e )
					{
						System.out.println( "Error: " + e.getMessage() );
						e.printStackTrace();
					}
					try
					{
						Context namingContext = new InitialContext();
						Core core = (Core)namingContext.lookup(url + "core");
						Order ord = core.getOrder(user.getUserName());

						textArea.setText("");
						for( Product prod : ord.getProducts().keySet() )
						{
							String pro = prod.getName();
							pro+=" price: "+prod.getPrice() + " number: " + ord.getProducts().get(prod);
							textArea.append(pro+"\n");
						}
						textArea.append("Total: "+ord.getTotal()+"\n");
					}
					catch( NamingException e ) 
					{
						System.out.println( "NamingError: " + e.getExplanation() ); 
					} 
					catch( Exception e ) 
					{
						System.out.println( "Error: " + e.getMessage() );
						e.printStackTrace();
					}
				}
				/*
				 * This is accepting the order set all op null;
				 * 
				 */
				else if( ae.getActionCommand().equalsIgnoreCase("Accepteren") )
				{
					System.setProperty( "java.security.policy", "client.policy" );
					try {
						Context namingContext = new InitialContext();
						Core core = (Core)namingContext.lookup(url + "core");
						core.placeOrder(userName);
						textArea.setText("Bestelling is geaccepteerd! Fine dag");
						@SuppressWarnings("unused")
						OrderGUI g = new OrderGUI(user);
						closeWindow();
					}
					catch( NamingException e ) 
					{
						System.out.println( "NamingError: " + e.getExplanation() ); 
					} 
					catch( Exception e ) 
					{
						System.out.println( "Error: " + e.getMessage() );
						e.printStackTrace();
					}
				}

				/*
				 * This is Cancel closes the GUI but saves User;
				 * 
				 */
				else
				{
					closeWindow();		
				}
			}
		});
	}

	private void closeWindow()
	{
		dispose();
	}

	private void input(String a)
	{
		statusLabel.setText(a + "!");
	}    
}